package com.cssl.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cssl.api.ApiUserLabel;
import com.cssl.dto.CreateOrderDTO;
import com.cssl.dto.DeplaneOrderDTO;
import com.cssl.entity.Equipment;
import com.cssl.entity.EquipmentRegion;
import com.cssl.entity.OrderForm;
import com.cssl.service.EquipmentRegionService;
import com.cssl.service.EquipmentService;
import com.cssl.service.OrderService;
import com.cssl.mapper.OrderMapper;
import com.cssl.util.UtilGenerateUUID;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @author 风止
* @description 针对表【order】的数据库操作Service实现
* @createDate 2025-03-13 11:50:00
*/
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderForm>
    implements OrderService{

    @Autowired
    private EquipmentRegionService eqs; //区域表
    @Autowired
    private EquipmentService es; //座位表
    @Autowired
    private ApiUserLabel userApi; //用户服务对外接口

    /**
     * 创建网费订单 （上机）
     * @param coDto
     * @return
     */
    //@GlobalTransactional(name="createOrder",rollbackFor = Exception.class)
    @Override
    public String createOrder(CreateOrderDTO coDto){
        try {
            //判断用户是否已经上机
            if(super.getBaseMapper().queryComputerNum(coDto.getNumber()) > 0)
                return "用户已经上过机了";
            String orderNumber = UtilGenerateUUID.GenerateUUID("Ord");
            super.baseMapper.insert(new OrderForm(
                    orderNumber,//订单编号
                    coDto.getNumber(), // 用户编号
                    coDto.getStart_time(), // 订单开始时间
                    coDto.getFavorable_id(), // 优惠ID
                    coDto.getEq_id(),
                    0
            ));

            //修改座位状态
            es.updateById(new Equipment(coDto.getEq_id(),1));

            return orderNumber;
        }catch (Exception exception){
            return "创建订单失败";
        }

    }

    /**
     * 查看用户的上机次数
     * @param number
     * @return
     */
    @Override
    public int queryComputerNum(int number) {
        return super.baseMapper.queryComputerNum(number);
    }


    /**
     * 用户下机
     * @param doDto
     * @return
     */
    @GlobalTransactional(name="order",rollbackFor = Exception.class)
    @Override
    public String deplane(DeplaneOrderDTO doDto) {
        //根据订单号查询出订单的创建时间
        OrderForm order = super.getById(doDto.getOrder_id());
        //根据座位编号查询出座位信息
        Equipment eq = es.getById(order.getEq_id());
        //根据座位信息中的区域编号查询出 网费价格
        EquipmentRegion er = eqs.getById(eq.getRegion_id());
        //计算上网时间（分钟）计算网费使用
        Duration duration = Duration.between(order.getStart_time(), doDto.getEnd_time());
        //转换分钟
        long minutes = duration.toMinutes();
        //计算网费 （0.15/分钟）
        DecimalFormat decimalFormat = new DecimalFormat("#.00"); //保留两位小数 （四舍五入）
        BigDecimal money = new BigDecimal(
                decimalFormat.format(
                        (double)minutes*(er.getRegion_price().doubleValue()/60)
                )
        );
        super.updateById(new OrderForm(
                doDto.getOrder_id(),
                doDto.getEnd_time(),
                money,
                doDto.getText(),
                doDto.getFavorable_id(),
                1
        ));

        //修改座位状态
        es.updateById(new Equipment(order.getEq_id(),2));

        //扣减用户余额 并返回结果是否成功
        return userApi.deductionMoney(order.getNumber(),money);
    }

    //*********当天需要的数据********************

    /**
     * 计算今日上机次数
     * @return
     */
    @Override
    public int computerNum() {
        return super.baseMapper.queryOrder();
    }

    /**
     * 计算今日收入
     * @return
     */
    @Override
    public double todayIncome() {
        return super.baseMapper.queryIncome();
    }

    /**
     * 查询当天的平均上机时间
     * @return
     */
    @Override
    public int findAverageTime() {
        return super.baseMapper.findAverageTime();
    }

    /**
     * 总上机时间
     * @return
     */
    @Override
    public int totalTime() {
        return super.baseMapper.findTotalTime();
    }

    //*********前一天需要的数据********************

    /**
     * 计算前天上机次数
     * @return
     */
    @Override
    public int computerNum_yd() {
        return super.baseMapper.queryOrder_yd();
    }

    /**
     * 计算前天收入
     * @return
     */
    @Override
    public double todayIncome_yd() {
        return super.baseMapper.queryIncome_yd();
    }

    /**
     * 查询前天的平均上机时间
     * @return
     */
    @Override
    public int findAverageTime_yd() {
        return super.baseMapper.findAverageTime_yd();
    }

    /**
     * 前天总上机时间
     * @return
     */
    @Override
    public int totalTime_yd() {
        return super.baseMapper.findTotalTime_yd();
    }

}




